package cn.fxl.user.service.impl;

import cn.fxl.basic.exception.BusinessExciption;
import cn.fxl.basic.result.AjaxResult;
import cn.fxl.basic.service.impl.BasicServiceImpl;
import cn.fxl.basic.utils.HttpUtil;
import cn.fxl.basic.utils.Md5Utils;
import cn.fxl.basic.utils.StrUtils;
import cn.fxl.system.domain.Menu;
import cn.fxl.system.mapper.MenuMapper;
import cn.fxl.system.mapper.PermissionMapper;
import cn.fxl.user.constant.WxConstants;
import cn.fxl.user.domain.Logininfo;
import cn.fxl.user.domain.User;
import cn.fxl.user.domain.Wxuser;
import cn.fxl.user.dto.LoginDto;
import cn.fxl.user.jwt.JwtUtils;
import cn.fxl.user.jwt.LoginData;
import cn.fxl.user.jwt.RsaUtils;
import cn.fxl.user.mapper.LogininfoMapper;
import cn.fxl.user.mapper.UserMapper;
import cn.fxl.user.mapper.WxuserMapper;
import cn.fxl.user.service.ILogininfoService;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.security.PrivateKey;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class LogininfoServiceImpl extends BasicServiceImpl<Logininfo> implements ILogininfoService {
    @Autowired
    private LogininfoMapper logininfoMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WxuserMapper wxuserMapper;
    @Autowired
    private PermissionMapper permissionMapper;
    @Autowired
    private MenuMapper menuMapper;
    @Override
    public AjaxResult accountLogin(LoginDto loginDto) {
        String account = loginDto.getAccount();
        String checkPass = loginDto.getCheckPass();
        Integer type = loginDto.getType();
        if(StringUtils.isEmpty(account) || StringUtils.isEmpty(checkPass)){
            throw new BusinessExciption("账号不能为空");
        }
        //获取登录信息
        Logininfo logininfo= logininfoMapper.getAccountLogin(loginDto);
        if(logininfo==null){
           throw new BusinessExciption("账号错误");
       }
       String password = logininfo.getPassword();
        String md5Psw = Md5Utils.encrypByMd5(checkPass+logininfo.getSalt());
        if(!password.equals(md5Psw)){
            throw new BusinessExciption("密码错误");
        }

        HashMap<String,Object> map=loginSuccessJwtHandler(logininfo);//jwt
        return new AjaxResult().setResultObj(map);
//        String token = UUID.randomUUID().toString();
//        logininfo.setPassword(null);
//        logininfo.setSalt(null);
//        HashMap<String, Object> map = new HashMap<>();
//        map.put("token",token);
//        map.put("logininfo",logininfo);
//        redisTemplate.opsForValue().set(token,logininfo,30, TimeUnit.MINUTES);

    }

    /**
     * jwt
     * @param logininfo
     * @return
     */
    private HashMap<String, Object> loginSuccessJwtHandler(Logininfo logininfo) {
        HashMap<String, Object> map = new HashMap<>();
        LoginData loginData = new LoginData();
        loginData.setLogininfo(logininfo);
        try {
            map.put("logininfo",logininfo);
            if(logininfo.getType()==0){
                List<String> permission = permissionMapper.loadPermissionSnByLogininfoId(logininfo.getId());
                map.put("permission",permission);
                loginData.setPermission(permission);
               List<Menu> menus= menuMapper.loadMenuByLogininfoId(logininfo.getId());
               map.put("menus",menus);
               loginData.setMenus(menus);
            }
            PrivateKey privateKey = RsaUtils.getPrivateKey(JwtUtils.class.getClassLoader().getResource("auth_rsa.pri").getFile());
            String jwtToken = JwtUtils.generateTokenExpireInMinutes(loginData, privateKey, 300000);
            map.put("token",jwtToken);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }

    @Override
    public AjaxResult wechatLogin(Map<String, String> map) {
        String code = map.get("code");
      String URL=  WxConstants.GET_ACK_URL.replace("APPID",WxConstants.APPID)
                .replace("SECRET",WxConstants.SECRET)
                .replace("CODE",code);
        String s = HttpUtil.httpGet(URL);
              /*  "access_token":"ACCESS_TOKEN",
                "expires_in":7200,
                "refresh_token":"REFRESH_TOKEN",
                "openid":"OPENID",
                "scope":"SCOPE",
                "unionid": "o6_bmasdasdsad6_2sgVt7hMZOPfL"*/
        JSONObject jsonObject = JSONObject.parseObject(s);
        String openid = jsonObject.getString("openid");
      Wxuser wxuser= wxuserMapper.getOneByOpenid(openid);
//        result.data.resultObj.token
       if(wxuser!=null && wxuser.getUserId()!=null && userMapper.getOne(wxuser.getUserId())!=null){
           User user=userMapper.getOne(wxuser.getUserId());
           Logininfo logininfo = logininfoMapper.getOne(user.getLogininfo_id());
           HashMap<String, Object> resultMap = loginSuccessJwtHandler(logininfo);
           return new AjaxResult().setResultObj(resultMap);
       }
       else {
//       ?accessToken="+accessToken+"&openId="+openId
           String token = jsonObject.getString("access_token");
           String openId = jsonObject.getString("openid");
           return AjaxResult.me().setSuccess(false).setResultObj("?accessToken="+token+"&openId="+openId);
       }
    }

    @Override
    public AjaxResult wechatBinder(Map<String, String> map) {
               /* phone:"13980835912",
                verifyCode:"",
                accessToken:"",
                openId:""*/
        String phone = map.get("phone");
        String verifyCode = map.get("verifyCode");
        String accessToken = map.get("accessToken");
        String openId = map.get("openId");
        if(StringUtils.isEmpty(verifyCode) || StringUtils.isEmpty(phone)){
            throw new BusinessExciption("信息不能为空");
        }
        Object o = redisTemplate.opsForValue().get("binder:"+phone);//binder:phone 验证码:时间戳
        if(o==null){
            throw new BusinessExciption("验证码过期了");
        }
        if (!o.toString().split(":")[0].equals(verifyCode)){
            throw new BusinessExciption("验证码错误");
        }
        String url=WxConstants.GET_USER_URL.replace("ACCESS_TOKEN",accessToken)
                                .replace("OPENID",openId);
        String jsonStr = HttpUtil.httpGet(url);
        JSONObject jsonObject = JSONObject.parseObject(jsonStr);

        Wxuser wxuser=jsonObject2Wxuser(jsonObject);
        User user = userMapper.getOneByPhone(phone);
        if(user==null){
           user = phone2User(phone);
            Logininfo logininfo= userLogininfo(user);
            logininfoMapper.save(logininfo);
            user.setLogininfo_id(logininfo.getId());
            userMapper.save(user);
        }
        wxuser.setUserId(user.getId());
        wxuserMapper.save(wxuser);
        Logininfo logininfo = logininfoMapper.getOne(user.getLogininfo_id());
        HashMap<String, Object> resultMap = loginSuccessJwtHandler(logininfo);
        return new AjaxResult().setResultObj(resultMap);
    }
                /*"openid":"OPENID",
                "nickname":"NICKNAME",
                "sex":1,
                "province":"PROVINCE",
                "city":"CITY",
                "country":"COUNTRY",
                "headimgurl": "http://wx.qlogo.cn/mmopen/g3MonUZtNHkdmzicIlibx6iaFqAc56vxLSUfpb6n5WKSYVY0ChQKkiaJSgQ1dZuTOgvLLrhJbERQQ4eMsv84eavHiaiceqxibJxCfHe/0",

        "unionid": " o6_bmasdasdsad6_2sgVt7hMZOPfL"*/
    private Wxuser jsonObject2Wxuser(JSONObject jsonObject) {
        Wxuser wxuser = new Wxuser();
        wxuser.setOpenid(jsonObject.getString("openid"));
        wxuser.setNickname(jsonObject.getString("nickname"));
        wxuser.setSex(Integer.parseInt(jsonObject.getString("sex")));
        wxuser.setHeadimgurl(jsonObject.getString("headimgurl"));
        wxuser.setUnionid(jsonObject.getString("unionid"));
        String country = jsonObject.getString("country");
        String province = jsonObject.getString("province");
        String city = jsonObject.getString("city");
        wxuser.setAddress(jsonObject.getString(country+province+city));
        return wxuser;
    }

    private User phone2User(String phone) {
        User user = new User();
        user.setUsername(phone);
        user.setPhone(phone);
        user.setState(1);
        String complexRandomString = StrUtils.getComplexRandomString(32);
        user.setSalt(complexRandomString);
        String password=Md5Utils.encrypByMd5(complexRandomString+StrUtils.getComplexRandomString(6));
        user.setPassword(password);
        return user;
    }

    private Logininfo userLogininfo(User user) {
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(user,logininfo);
        logininfo.setType(1);
        logininfo.setDisable(true);
        return logininfo;
    }
}
